package com.dys.servlet;

import com.dys.entity.User;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * @Author: 疾风
 * @ClassName: Servlet01
 * @Description: EL表达式
 * @CreateDate: 2024/09/24
 * @Version: v1.0.0
 */
@WebServlet(urlPatterns = "/servlet01.do")
public class Servlet01 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.向三个域中放入数据
        // 1.1 向请求域中放入数据
        User huge = new User(1, "胡歌", "123");
        req.setAttribute("user1",huge);
        req.setAttribute("msg","请求域数据");

        // 1.2 向Session域中放入数据
        HttpSession session = req.getSession();
        List<User> list = new ArrayList<>();
        User user1 = new User(2, "赵丽颖", "123456");
        User user2 = new User(3, "迪丽热巴", "123456");
        User user3 = new User(4, "关晓彤", "123456");
        Collections.addAll(list,user1,user2,user3);
        session.setAttribute("users",list);
        session.setAttribute("msg","Session域放入数据");

        // 1.3 向Application域中放入数据
        ServletContext application = req.getServletContext();
        Map<String, User> map = new HashMap<>();
        map.put("a",user1);
        map.put("b",user2);
        map.put("c",user3);
        application.setAttribute("userMap",map);
        application.setAttribute("msg","Application域");

        // 获取请求中的参数
        // http://localhost:8080/servlet_el01_Web_exploded/servlet01.do?username=lisi&hobby=1&hobby=2
        String username = req.getParameter("username");
        System.out.println("请求中的用户名："+username);
        String[] hobbies = req.getParameterValues("hobby");
        System.out.println("爱好："+Arrays.toString(hobbies));

        // 跳转到jsp页面
        req.getRequestDispatcher("showInfo.jsp").forward(req, resp);
    }
}
